package com.group01.community.utils;

import com.group01.community.entity.SysDept;
import com.group01.community.entity.vo.SysDeptVo;


import java.util.ArrayList;
import java.util.List;

public class DeptTreeUtils {

        /**
         *  流程：数据库查出的菜单记录装在承载菜单的列表中
         *  构建树（获取根节点，遍历根节点，对每一个根节点构建子树）---得到最终树形菜单
         *  承载菜单的列表
         */
        private List<SysDeptVo> deptList = new ArrayList<>();

        public DeptTreeUtils(List<SysDeptVo> deptList){
            this.deptList = deptList;
        }

        /**
         * 获取根节点
         * @return
         */
        private List<SysDeptVo> getRootNode(){
            List<SysDeptVo> rootNode = new ArrayList<>();

            if(deptList.size() > 99){
                for (SysDeptVo dept: deptList) {
                    if (0 == dept.getParentId()) {
                        rootNode.add(dept);
                    }
                }
            }else {
                for (int i = 0; i <= deptList.size() - 1; i++) {
                    if(0 == deptList.get(i).getParentId()){
                        rootNode.add(deptList.get(i));
                    }else {
                        boolean f = true;
                        for (int j = 0; j <= deptList.size() - 1; j++) {
                            if (deptList.get(i).getParentId().equals(deptList.get(j).getDeptId())) {
                                f = false;
                            }
                        }
                        if(f){
                            rootNode.add(deptList.get(i));
                        }

                    }

                }
            }

            return rootNode;
        }

        /**
         * 构建子树
         * @param rootNode 子节点
         * @return
         */
        private SysDeptVo builddepts(SysDeptVo rootNode){
            List<SysDeptVo> deptsTree = new ArrayList<>();
            for (SysDeptVo dept : deptList) {
                if (dept.getParentId().equals(rootNode.getDeptId())){
                    deptsTree.add(builddepts(dept));
                }
            }
            rootNode.setDepts(deptsTree);
            return rootNode;
        }

        /**
         * 构建树
         * @return
         */
        public List<SysDeptVo> buildTree(){
            List<SysDeptVo> depts = getRootNode();
            for (SysDeptVo dept : depts) {
                builddepts(dept);
            }
            return depts;
        }
    }

